import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:orginone/components/EmptyWidget/EmptyWidget.dart';

/// 懒加载数据
class XLazy<T> extends StatelessWidget with EmptyMixin<T> {
  /// 初始化数据
  final List<T> initDatas;

  /// 初始化加载
  final FutureOr<dynamic> Function()? onInitLoad;

  /// 加载更多数据
  final FutureOr<dynamic> Function()? onLoad;

  /// 滚动条控制器
  final ScrollController? scrollController;

  /// 数据项构建
  final Widget Function(BuildContext, List<T> datas) builder;

  const XLazy(
      {Key? key,
      this.initDatas = const [],
      required this.onInitLoad,
      this.onLoad,
      required this.builder,
      this.scrollController})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return null != onLoad
        ? _buildMoreLazyWidget(context)
        : _buildWidget(context);
  }

  Widget _buildMoreLazyWidget(BuildContext context) {
    return EasyRefresh(
        // footer: const ClassicFooter(
        //   // triggerOffset: 110,
        //   dragText: '上拉加载',
        //   processingText: '正在加载',
        //   noMoreText: '',
        //   // noMoreText: '--没有更多--',
        //   readyText: '准备加载',
        //   armedText: '正在加载',
        //   // processedText: '--没有更多--',
        //   processedText: '',
        //   failedText: '加载失败',
        //   // messageText: '最新加载： %T',
        //   messageText: '',
        //   noMoreIcon: null,
        //   iconDimension: 0,
        //   iconTheme: null,
        //   failedIcon: null,
        //   succeededIcon: null
        // ),
        // footer: const NotLoadFooter(),
        footer: const MaterialFooter(),
        refreshOnStart: initDatas.isEmpty,
        notLoadFooter: const NotLoadFooter(),
        onLoad: onLoad,
        scrollController: scrollController,
        child: buildEmptyWidget(initDatas.isEmpty, _buildItem(context, null)));
  }

  Widget _buildWidget(BuildContext context) {
    return null != onInitLoad
        ? _buildLazyWidget(context)
        : _buildContent(context, initDatas);
  }

  Widget _buildLazyWidget(BuildContext context) {
    return FutureBuilder<List<T>>(
        future: Future(onInitLoad as FutureOr<List<T>> Function()),
        builder: (context, sho) {
          if (sho.connectionState == ConnectionState.done) {
            return _buildContent(context, sho.data);
          }
          return const Center(
            child: CircularProgressIndicator(),
          );
        });
  }

  Widget _buildContent(BuildContext context, List<T>? datas) {
    return buildEmptyWidget(
        datas?.isEmpty ?? initDatas.isEmpty, _buildItem(context, datas));
  }

  /// 构建懒加载项
  Widget _buildItem(BuildContext context, List<T>? datas) {
    return builder(context, datas ?? initDatas);
  }
}
